
import PlatformUtil from "./PlatformUtil";
import NumberView from "./NumberView";
import httpUtils from "./XmlHttpTool";
import allVariableJs from "./allVariable";
const base64 = require('./Tool/base64.js');
import xorEncryptionData from "./Tool/xor";
cc.Class({

    extends: cc.Component,

    properties: {

        startGameBtn:cc.Button,
        numberCompontent:NumberView,
        energyCompontent:NumberView,
        bgMusicSound:{
            default: null,
            type: cc.AudioClip
        },
        topView:cc.Node,
        logonode:cc.Node,
        wordListView:cc.Node,
        wordShowView:cc.Node,
        friendListView:cc.Node,
        bageAllScrollView:cc.Node,
        inviteBtn:cc.Button,
        rankBtn:cc.Button,
        moreBtn:cc.Button,
        shopBtn:cc.Button,
        moreContentView:cc.Node,
        showHubProjess:cc.Node,
        SvprogressPrefab: cc.Prefab,
        userEnergy:cc.Integer,
        addenergyBtn:cc.Button,
        insufficientAllView:cc.Node,
        insufficientClose:cc.Button,
        playNowBtn:cc.Button,
        exchangeEnergyView:cc.Node,
        isshareSuccess:cc.Boolean,
        baseSource:"",
        preloadedRewardedVideo: "",
        videoBtn:cc.Button,
        chooseMarkView:cc.Node
       

    },

    enterGameViewClick:function(){
        // sdkbox.PluginAdMob.hide("home")
       
          
          if(this.userEnergy>0){
            console.log("开始游戏")

            if(cc.isValid(this.showHubProjess)){
              this.showHubProjess.destroy();
            }
            this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
            this.node.addChild(this.showHubProjess);
            this.showHubProjess.getComponent('SVProgressView').init("loading...")
      
             let finish = cc.callFunc(() => { 
            
              this.showHubProjess.destroy();
          
            }, this);
          let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(3), cc.fadeOut(1), finish);
          this.showHubProjess.runAction(action);



              var changebig2 = cc.scaleTo(0.2,1.1);
  
              var finish = cc.callFunc(function(){
          
                var changesmail2 = cc.scaleTo(0.1,1.0);
                this.startGameBtn.node.runAction(changesmail2)
          
             }, this);
          
             var seq = cc.sequence(changebig2,finish)
          
              this.startGameBtn.node.runAction(seq)
      
              cc.director.loadScene("GameSence",function(){
      
                  var mainNode= cc.find("Canvas/backgroundtop")
      
                  mainNode.getComponent("backgrould").onAgainSence();
      
      
             });
               
          }else{
  
             console.log("Loss of energy!")
            this.chooseMarkView.active=true
            this.videoBtn.node.active=true

          }
    },


    videoStartClick:function(){

      this.chooseMarkView.active=false
      this.videoBtn.node.active=false
      
      var self = this
      if(this.preloadedRewardedVideo){
        this.preloadedRewardedVideo.showAsync()
  
        .then(function () {
          // 播放成功
          var _this = self
          httpUtils.httpPost("/marmot/ads_to_energy", {}, function (res) {
  
            var flagstr = res.flag_key + PlatformUtil.platform.params["appver"]
            var resultstr = xorEncryptionData.encryptionData(flagstr, PlatformUtil.platform.params)
            console.log("正常播放,可以发游戏奖励", flagstr)
            httpUtils.NhttpPost("/marmot/ads_to_energy", { "flag_key": resultstr, "keysid": res.keysid }, function (res) {
              console.log("广告体力请求接口", JSON.stringify(res))
              _this.energyCompontent.setText(parseInt(res["energy"]))
            }, function (failres) {
              console.log("广告体力请求接口失败", JSON.stringify(failres))
            })
          })
        }).catch(function (e) {
  
          console.log("广告播放失败", e);
          self.popBranerAdCode();  
  
        });
      }else{
        self.popBranerAdCode(); 
      }
      
    },


    popBranerAdCode:function(){

      var _this = this
  
      allVariableJs.preloadedBrannerAd.showAsync()
        .then(function () {
            
          httpUtils.httpPost("/marmot/ads_to_energy", {}, function (res) {
  
            var flagstr = res.flag_key + PlatformUtil.platform.params["appver"]
            var resultstr = xorEncryptionData.encryptionData(flagstr, PlatformUtil.platform.params)
            console.log("正常播放,可以发游戏奖励", flagstr)
          
            httpUtils.NhttpPost("/marmot/ads_to_energy", { "flag_key": resultstr, "keysid": res.keysid }, function (res) {
              console.log("广告体力请求接口", JSON.stringify(res))
              _this.getUserInfoHttp()

              if(cc.isValid(_this.showHubProjess)){
                _this.showHubProjess.destroy();
              }
              _this.showHubProjess = cc.instantiate(_this.SvprogressPrefab);
              _this.node.addChild(_this.showHubProjess);
              _this.showHubProjess.getComponent('SVProgressView').init("Get energy")
        
               let finish = cc.callFunc(() => { 
              
                _this.showHubProjess.destroy();
            
              },_this);
            let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(3), cc.fadeOut(1), finish);
            _this.showHubProjess.runAction(action);


            }, function (failres) {
              console.log("广告体力请求接口失败", JSON.stringify(failres))
            })
          })
  
          FBInstant.getInterstitialAdAsync(
  
            '1115286701982920_1147074248804165', 
          ).then(function (rewarded) {
  
            allVariableJs.preloadedBrannerAd = rewarded;
  
            return allVariableJs.preloadedBrannerAd.loadAsync();
  
          }).then(function () {
     
          }).catch(function (err) {
   
          });
          console.log("结束游戏弹出插屏广告成功");
             
        }).catch(function (e) {
          // 播放失败
          console.log("结束游戏弹出广告失败跳转分享", e);
    
          _this.noAnimviteShare();
          
        });
  
    },
    
    onLoad () {

      
        if(allVariableJs.isMusicPlaying){


        }else{
           
           this.current = cc.audioEngine.play(this.bgMusicSound, true, 1);
           allVariableJs.isMusicPlaying=true
        }


        var changebig2 = cc.scaleTo(0.2,1.2);

        var finish = cc.callFunc(function(){

        var changesmail2 = cc.scaleTo(0.1,1.0);
        this.logonode.runAction(changesmail2)

    }, this);

     var seq = cc.sequence(changebig2,finish)

     this.logonode.runAction(seq)


     var self = this

     FBInstant.getRewardedVideoAsync(
       '1115286701982920_1144618379049752', // Your Ad Placement Id
     ).then(function (rewarded) {
       self.preloadedRewardedVideo = rewarded;
       return self.preloadedRewardedVideo.loadAsync();
     }).then(function () {
       console.log("广告数组", self.preloadedRewardedVideo)
     }).catch(function (err) {
       console.log("广告加载错误", err);
       console.log("变量", self.preloadedRewardedVideo);
     });


     FBInstant.getInterstitialAdAsync(

           '1115286701982920_1147074248804165', // Your Ad Placement Id
     
      ).then(function(rewarded) {

             allVariableJs.preloadedBrannerAd = rewarded;

            return allVariableJs.preloadedBrannerAd.loadAsync();

     }).then(function(){
           console.log("插频广告数组",allVariableJs.preloadedBrannerAd)
     }).catch(function(err){
         console.log("插屏广告加载错误",err);
         console.log("插屏广告变量",allVariableJs.preloadedBrannerAd);
     });

    },


    insufficientCloseClick:function(){

        this.insufficientAllView.active=false
    },

    
    getUserInfoHttp:function(){
  
        var that= this
        httpUtils.NhttpPost("/marmot/user_info",{},function(res){

            console.log("用户信息",JSON.stringify(res))  
           
            var stars =parseInt(res["ticket_num"])
            var energy=parseInt(res["energy_num"])
            that.userEnergy=energy
            that.numberCompontent.setText(stars)
            that.energyCompontent.setText(energy)
            


        },function(failres){
          console.log("用户信息请求是吧",JSON.stringify(failres))  
        }) 

    },

     
    addEnergyClick:function(){
        console.log("增加体力")

        this.exchangeEnergyView.active=true

    },


    chargeEnergyClick:function(){

         var that= this
        httpUtils.NhttpPost("/marmot/star2energy",{},function(res){
            console.log("兑换体力成功",JSON.stringify(res))  
            that.getUserInfoHttp()

            if(cc.isValid(that.showHubProjess)){
                that.showHubProjess.destroy();
              }
              that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
              that.node.addChild(that.showHubProjess);
              that.showHubProjess.getComponent('SVProgressView').init("Get energy")
        
               let finish = cc.callFunc(() => { 
              
                that.showHubProjess.destroy();
            
              }, that);
            let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(0.5), cc.fadeOut(1), finish);
            that.showHubProjess.runAction(action);

           
        },function(failres){
            console.log("兑换体力失败",JSON.stringify(failres))  
            that.insufficientAllView.active=true
        }) 


    },
  
    noAnimviteShare:function(){

      var self=this
      httpUtils.NhttpPost("/wxmp/marmot/share_msg",{"type":"link","link":"http://www.taoqi001.com/","title":"TapTapMoles","text":"Best Game Engine"},function(res){
  
       console.log('分享成功数据',JSON.stringify(res))
      
       var _this=self
       var dataimageurl=res["image"]
       console.log("分享图片url",dataimageurl)
       self.loadImg2Base64(dataimageurl,function(baseData){
   
          
           _this.baseSource=baseData
           console.log("转化后的baseUrl数据",_this.baseSource)
   
           FBInstant.shareAsync({
   
               intent: 'SHARE',
               image: _this.baseSource,
               text: 'X is asking for your help!',
               data: { myReplayData: '...' },
             
           }).then(function(data) {
               // 继续游戏
               console.log("分享结果",data)
   
               var that= _this
   
               httpUtils.NhttpPost("/wxmp/marmot/share",{},function(shareres){
   
                   console.log('分享加体力',JSON.stringify(shareres))

                   if(shareres["success"]==true){
                    if(cc.isValid(that.showHubProjess)){
                      that.showHubProjess.destroy();
                    }
                    that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
                    that.node.addChild(that.showHubProjess);
                    that.showHubProjess.getComponent('SVProgressView').init("Get energy")
              
                     let finish = cc.callFunc(() => { 
                    
                      that.showHubProjess.destroy();
                  
                    }, that);
                  let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(4), cc.fadeOut(1), finish);
                  that.showHubProjess.runAction(action);
                   }else{
                    if(cc.isValid(that.showHubProjess)){
                      that.showHubProjess.destroy();
                    }
                    that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
                    that.node.addChild(that.showHubProjess);
                    that.showHubProjess.getComponent('SVProgressView').init(shareres["tip"])
              
                     let finish = cc.callFunc(() => { 
                    
                      that.showHubProjess.destroy();
                  
                    }, that);
                  let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(4), cc.fadeOut(1), finish);
                  that.showHubProjess.runAction(action);
                   }
   
                   that.getUserInfoHttp();
      
               })         
           });
   
       })
      },function(failres){
         console.log('分享失败',failres) 
      });
    },


    
    inviteShare:function(){

    console.log("邀请好友一起玩ss")

    if(cc.isValid(this.showHubProjess)){
      this.showHubProjess.destroy();
    }
    this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
    this.node.addChild(this.showHubProjess);
    this.showHubProjess.getComponent('SVProgressView').init("share...")

     let finish = cc.callFunc(() => { 
    
      this.showHubProjess.destroy();
  
    }, this);
  let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(3), cc.fadeOut(1), finish);
  this.showHubProjess.runAction(action);


    var changebig2 = cc.scaleTo(0.2,1.1);

    var finish = cc.callFunc(function(){

      var changesmail2 = cc.scaleTo(0.1,1.0);
      this.inviteBtn.node.runAction(changesmail2)


   }, this);

    var seq = cc.sequence(changebig2,finish)

    this.inviteBtn.node.runAction(seq)

    var self=this
    httpUtils.NhttpPost("/wxmp/marmot/share_msg",{"type":"link","link":"http://www.taoqi001.com/","title":"TapTapMoles","text":"Best Game Engine"},function(res){

     console.log('分享成功数据',JSON.stringify(res))
    
     var _this=self
     var dataimageurl=res["image"]
     console.log("分享图片url",dataimageurl)
     self.loadImg2Base64(dataimageurl,function(baseData){
 
        
         _this.baseSource=baseData
         console.log("转化后的baseUrl数据",_this.baseSource)
 
         FBInstant.shareAsync({
 
             intent: 'SHARE',
             image: _this.baseSource,
             text: 'X is asking for your help!',
             data: { myReplayData: '...' },
           
         }).then(function(data) {
             // 继续游戏
             console.log("分享结果",data)
 
             var that= _this
 
             httpUtils.NhttpPost("/wxmp/marmot/share",{},function(shareres){
 
                 console.log('分享加体力',JSON.stringify(shareres))
 
                 that.getUserInfoHttp();
                 if(shareres["success"]==true){
                  if(cc.isValid(that.showHubProjess)){
                    that.showHubProjess.destroy();
                  }
                  that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
                  that.node.addChild(that.showHubProjess);
                  that.showHubProjess.getComponent('SVProgressView').init("Get energy")
            
                   let finish = cc.callFunc(() => { 
                  
                    that.showHubProjess.destroy();
                
                  }, that);
                let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(4), cc.fadeOut(1), finish);
                that.showHubProjess.runAction(action);
                 }else{
                  if(cc.isValid(that.showHubProjess)){
                    that.showHubProjess.destroy();
                  }
                  that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
                  that.node.addChild(that.showHubProjess);
                  that.showHubProjess.getComponent('SVProgressView').init(shareres["tip"])
            
                   let finish = cc.callFunc(() => { 
                  
                    that.showHubProjess.destroy();
                
                  }, that);
                let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(4), cc.fadeOut(1), finish);
                that.showHubProjess.runAction(action);
                 }
 
             
             })
         
         });
 
     })

    },function(failres){
       console.log('分享失败',failres) 
    });


   
  },


  loadImg2Base64(url, callback) {

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
    console.log("xhr.readyState " + xhr.readyState);
    console.log("xhr.status " + xhr.status);
    if (xhr.readyState === 4) {
    if (xhr.status === 200) {
        console.log("success");
    let data = new Uint8Array(xhr.response);
    let base = "data:image/png;base64," + base64.Base64.encodeArr(data);
    callback(base);
    }
    }
    };
    xhr.responseType = 'arraybuffer';
    xhr.open("GET", url, true);
    xhr.onerror = function(e) {
          
        console.log('转化图片错误',e)
    };
    xhr.send();
    },




  rankView:function(){

    console.log("排行榜");
  
    var changebig2 = cc.scaleTo(0.2,1.1);

    var finish = cc.callFunc(function(){

      var changesmail2 = cc.scaleTo(0.1,1.0);
      this.rankBtn.node.runAction(changesmail2)
      this.wordListView.active=true
      this.wordShowView.getComponent("facebookScrollView").init()

   }, this);

    var seq = cc.sequence(changebig2,finish)

    this.rankBtn.node.runAction(seq)

  },

  bageView:function(){

    console.log("兑换包裹");
  },

  moreView:function(){

    console.log("更多");
    
    var changebig2 = cc.scaleTo(0.2,1.1);

    var finish = cc.callFunc(function(){

      var changesmail2 = cc.scaleTo(0.1,1.0);
      this.moreBtn.node.runAction(changesmail2)
      this.moreContentView.getComponent("bageScrollView").init()
      this.bageAllScrollView.active=true

   }, this);

    var seq = cc.sequence(changebig2,finish)

    this.moreBtn.node.runAction(seq)

  },
  
    start () {

    },

});
